package top.linuyx.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import top.linuyx.enums.ResponseEnum;
import top.linuyx.pojo.param.AccountLoginParam;
import top.linuyx.pojo.param.AccountRegisterParam;
import top.linuyx.pojo.response.ResponseData;
import top.linuyx.service.AccountService;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Arrays;

/**
 * @Author Linuyx
 * @Description AccountController
 * @Date Created in 2021-04-09 8:45
 */

@Controller
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping(value = "/please-login", name = "请登录")
    @ResponseBody
    public ResponseData<String> pleaseLogin() {
        return ResponseData.fail(
                ResponseEnum.AUTHENTICATE_ERROR.getCode(),
                ResponseEnum.AUTHENTICATE_ERROR.getMessage()
        );
    }

    @PostMapping(value = "/register", name = "注册")
    @ResponseBody
    public ResponseData<String> register(@Valid @RequestBody AccountRegisterParam registerParam) {
        //给用户添加角色
        registerParam.setRoles(Arrays.asList("user"));

        accountService.register(registerParam);
        return ResponseData.success("注册成功");
    }

    @PostMapping(value = "/insert-admin", name = "添加管理员")
    @RequiresRoles("super_admin")
    @ResponseBody
    public ResponseData<String> insertAdmin(@Valid @RequestBody AccountRegisterParam registerParam){
        //给管理员添加角色
        registerParam.setRoles(Arrays.asList("admin","user"));

        accountService.register(registerParam);
        return ResponseData.success("添加成功");
    }

    @PostMapping(value = "/login", name = "登录")
    @ResponseBody
    public ResponseData<String> login(@Valid @RequestBody AccountLoginParam loginParam) {
        //设置角色
        loginParam.setRole("user");

        accountService.login(loginParam);
        return ResponseData.success("登录成功");
    }

    @PostMapping(value = "/login/admin", name = "管理员登录")
    @ResponseBody
    public ResponseData<String> loginAdmin(@Valid @RequestBody AccountLoginParam loginParam) {
        //设置角色
        loginParam.setRole("admin");

        accountService.login(loginParam);
        return ResponseData.success("登录成功");
    }

    @GetMapping(value = "/logout", name = "退出登录")
    @ResponseBody
    public ResponseData<String> logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResponseData.success("退出成功");
    }

    @GetMapping("/index")
    @ResponseBody
    public ResponseData<String> index(HttpSession session) {
        return ResponseData.success("首页");
    }

}
